﻿
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;

namespace ConsoleDemo
{
    class Program
    {
        static void Main(string[] args)
        {
           IConfigurationRoot root = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .Build();

            var services = new ServiceCollection();
            services.AddOptions();
            services.Configure<TestOptions>(root.GetSection("test"));

            var provider = services.BuildServiceProvider();

            Console.WriteLine("原始值：");
            ShowOptions(provider);
            Console.WriteLine("修改配置文件");
            Console.ReadLine();
            ShowOptions(provider);

            Console.ReadKey();
        }

        /// <summary>
        /// 显示所有的选项
        /// </summary>
        static void ShowOptions(IServiceProvider serviceProvider)
        {
            using (var scope = serviceProvider.CreateScope())
            {
                var sp = scope.ServiceProvider;
                var options = sp.GetRequiredService<IOptions<TestOptions>>();
                var monitor = sp.GetRequiredService<IOptionsMonitor<TestOptions>>();
                var snapshot = sp.GetRequiredService<IOptionsSnapshot<TestOptions>>();

                Console.WriteLine($"options:{options.Value.name}");
                Console.WriteLine($"monitor:{monitor.CurrentValue.name}");
                Console.WriteLine($"snapshot:{snapshot.Value.name}");
            }
        }
       
        public class TestOptions
        {
            /// <summary>
            /// 名称
            /// </summary>
            public string name { get; set; }
        }
    }
}
